'use strict';
import React, {Component} from 'react';

import {
    View,
    Image,
    ImageBackground,
    Dimensions,
    TouchableWithoutFeedback,
    StyleSheet,
    Text,
    TouchableOpacity,
    TextInput,
    ScrollView,
    TouchableHighlight,
    TouchableNativeFeedback,
    Switch,
    Modal,
    ART
} from 'react-native';

import ToastUtil from '../../../../core/utils/toast-util';
import {Loading, EasyLoading} from 'react-native-easy-loading';
import ImagePicker from 'react-native-image-crop-picker';

import Color from '../../../../core/constant/color';
import InitDB from '../../../../core/database/init-db';
import Util from '../../../../core/utils/util';
import ModalDropdown from '../../../../core/component/comp.modal-dropdown';
import GridView from '../../../../core/component/comp.grid-view';
import ImageComponent from '../../../../core/component/comp.image.js';
import ImageButton from "../../../../core/component/comp.image-button";


class MineScene extends React.Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        title: "我的",
        headerTintColor: "white",
        headerStyle: {
            backgroundColor: Color.PRIMARY_COLOR,
            elevation: null

        },
    });

    // 构造
    constructor(props) {
        super(props);
        this.state = {
            addPicModalVisible: '0',
            xiangce_urls: ['addPic'],

        }
        this.picView.bind(this);
        this.genPeopleInfoItemUI.bind(this);
    }

    componentDidMount() {
        //Http.post_dbFile();
        //ToastUtil.show('aaaa');

        Promise.resolve().then(EasyLoading.show('loading...', 5000));
        let touxiangUrl, videoUrl, nickName, current_huiyuan, xiangece;
        let userInfo = InitDB.getUserInfo("ACVT_CODE='userinfo'");
        for (var i = 0; i < userInfo.length; i++) {
            var obj = userInfo[i];
            //ToastUtil.show("QST_CODE:"+obj.QST_CODE);
            if (obj.QST_CODE === 'touxiang') {
                touxiangUrl = Util.substrImageUrl(obj.OPT_VAL);
            } else if (obj.QST_CODE === 'video') {
                videoUrl = obj.OPT_VAL;
                if (videoUrl) {
                    videoUrl = Util.substrImageUrl(obj.OPT_VAL);
                }

            } else if (obj.QST_CODE === 'nick_name') {
                nickName = obj.OPT_VAL;

            } else if (obj.QST_CODE === 'current_huiyuan') {
                current_huiyuan = obj.OPT_VAL;
            } else if (obj.QST_CODE === 'xiangce') {
                if (obj.OPT_VAL) {

                    obj.OPT_VAL.split(",").map((item, i) => {
                        this.state.xiangce_urls.push(item);
                    })
                }
            }

        }

        this.setState({
            touxiangUrl: touxiangUrl,
            nickName: nickName,
            videoUrl: videoUrl,
            current_huiyuan: current_huiyuan,

        })


        Promise.resolve().then(EasyLoading.dismis());

    }

    setProperty(name, value) {
        this.setState({
            [name]: value
        })
    }


    touxiangMenu() {
        this.setState({modalVisible: true});
    }

    changeTouxiang(text) {
        ToastUtil.show('你选择了:' + text);
    }


    _setModalVisible(visible) {
        alert("d");
        this.setState({modalVisible: visible});
    }

    touxiangChakan() {
        const that = this;
        this.props.screenProps.appNavigation.navigate('Touxiang', {
            operatorType: "update", callback(imageIndex, touxiangUrl) {
                that.setState({
                    touxiangUrl: touxiangUrl,
                })
            }
        });
    }

    setting() {
        // this.props.screenProps.appNavigation.navigate('Setting');
        const {navigate} = this.props.navigation;
        navigate('SettingScene');

    }

    onPressJumpToAPIList() {
        this.props.navigation.navigate('ApiList');
    }

    genHeaderUI_old() {
        return (
            <View>
                <TouchableWithoutFeedback onPress={this.touxiangChakan.bind(this)}>
                    <ImageBackground style={{
                        marginLeft: 0,
                        marginRight: 0,
                        height: 200,
                        flexDirection: 'row',
                        justifyContent: 'center',
                        alignItems: "center"
                    }} source={{url: this.state.touxiangUrl, cache: 'force-cache'}}>
                        <VideoSpzt style={{position: "absolute", left: 2, top: 2}}/>
                        <View>
                            <Image source={require('../../../../img/bofang.png')}/>
                        </View>
                    </ImageBackground>
                </TouchableWithoutFeedback>
            </View>
        );
    }

    onPressJumpToSkillDetail = () => {

        const skillInfo = {
            "id": 1,
            "person_id": 17,
            "price": 20,
            "skillDesc": "擅长中下，全时间段接单",
            "spzt": "1",
            "voice": "selfDescription",
            "zizhitu": "wangzherongyao_zizhi_template",
            "emp_id": 17,
            "nick_name": "小铃铛",
            "grade_id": 433,
            "skill_id": 16,
            "orderNumber": 11,
            "evaluateNumber": 5,
            "orderNumber30": 10,
            "orderNumber7": 4,
            "xinyong": 3,
            "state": "1",
            "systemDesc": "QQ区 强势核心 全区有号",
            "unit": "半小时",
            "zizhitu_url": "wangzherongyao_zizhi_template@/media/235.jpg",
            "voice_url": "selfDescription@/media/230.mp3",
            "skill_name": "白银大叔",
            "age": "27",
            "gender": "2",
            "times": "4天8小时52分钟",
            "touxiang_url": "touxiang_template@/media/237.jpg",
            "city_id": 175,
            "city_name": "上海市",
            "rownum": 1
        }

        this.props.navigation.navigate('SkillDetailScene', {title: this.state.nickName, skillInfo: skillInfo})
    }

    onPressJumpToMyMoney=()=>{
        this.props.navigation.navigate('MyMoneyScene', {title: '我的钱包'})
    }

    genHeaderUI() {
        return (
            <View style={styles.headerPanel}>
                <TouchableOpacity onPress={this.onPressJumpToSkillDetail}>
                    <View style={styles.headerPanelBg} source={require('../../images/mine/mine_head_bg.png')}>
                        <Image style={styles.headerTopLeft} source={{url: this.state.touxiangUrl}}/>
                        <View style={styles.headerTopMid}>
                            <Text style={styles.headerNickName}>{this.state.nickName}</Text>
                            <Text style={styles.headerID}>ID: 0000000</Text>
                        </View>
                        <ImageButton style={styles.btnNext} imageStyle={styles.btnNextImage}
                                     source={require('../../images/mine/mine_head_more.png')}/>
                    </View>
                </TouchableOpacity>
                <TouchableOpacity onPress={this.onPressJumpToMyMoney}>
                    <View style={styles.headerBottomPanel}>
                        <View style={styles.headerLeft}>
                            <Text style={styles.accountTitle}>2000.0</Text>
                            <Text style={styles.accountBottomTitle}>账户余额</Text>
                        </View>
                        <View style={styles.headerMid}>
                            <Text style={styles.accountTitle}>200</Text>
                            <Text style={styles.accountBottomTitle}>钻石</Text>
                        </View>
                        <View style={styles.headerRight}>
                            <Text style={styles.accountTitle}>100</Text>
                            <Text style={styles.accountBottomTitle}>礼物收益</Text>
                        </View>
                        <ImageButton style={styles.btnNext} imageStyle={styles.btnNextImageSmall}
                                     source={require('../../images/mine/mine_head_more.png')}/>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }

    genTableRowUI(info, index) {
        return (
            <View key={`item-tab-row-${index}`} style={styles.tableRowItemPanel}>
                <TouchableOpacity onPress={info.onPress}>
                    <View style={styles.tableRowTouch}>
                        <View style={styles.input_label_view}>
                            {info.icon && <Image style={styles.tableRowIcon} source={info.icon}/>}
                            <Text style={styles.input_label_text}>{info.title}</Text>
                        </View>
                        <View style={styles.input_value_view}>
                            <Text style={styles.input_value_text}>{info.rightTitle}</Text>
                            {info.rightButton && <View style={styles.tipBox}>
                                <Text style={{color: '#ffffff'}}>{info.rightButton.title}</Text>
                            </View>}
                            {info.jumpArrow &&
                            <Image style={styles.arrowIcon} source={require('../../images/mine/mine_head_more.png')}/>}
                        </View>
                    </View>
                </TouchableOpacity>
                {info.showSplite && <View style={styles.tableRowSplit}/>}
            </View>
        );
    }

    addPic(value) {
        if (value === '取消') {
            this.setState({
                addPicModalVisible: '0'
            })
            return;
        }

        let getImag;
        if (value === '拍照') {
            getImag = ImagePicker.openCamera({
                multiple: true,

            });
        } else if (value === '从手机相册选择') {

            getImag = ImagePicker.openPicker({
                multiple: true,
            });
        }

        getImag.then(images => {
            this.setState({
                addPicModalVisible: '0'
            })
            let fc = 'xiangce_add';
            let xiangceUrls = this.state.xiangce_urls;
            let imageIdex = Util.uuid();
            images.map((item, i) => {

                let uri = item.path;
                xiangceUrls.push(uri);

            })
            console.log(xiangceUrls, 'xiangceUrls');
            this.setState({
                xiangce_urls: xiangceUrls
            })

            /*Http.post_image(fc, uri, imageIdex, photokey)
                .then((data) => {
                    console.log(data);
                    let empId = InitDB.getCurrentUser().empId;
                    let params = { touxiang: imageIdex }

                    Http.post_upload(fc, empId, params).then((data) => {

                        InitDB.updateUserInfoProperty('touxiang', imageIdex + "@" + uri);


                    })


                    console.log(images);
                })
                */
        }).catch((err) => {
            this.setState({
                addPicModalVisible: '0'
            })
        })
    }

    picView(url) {
        if (url === this.state.xiangce_urls[0]) {

        }
    }

    genPeopleInfoItemUI(item, i, groupIndex) {
        let url = Util.substrImageIndex(item);
        let chicun = parseInt((Util.getScreenWidth() - 36) / 3);
        let totalIndex = groupIndex * 3 + i;
        if (this.state.xiangce_urls.length % 3 != 0 && totalIndex >= parseInt(this.state.xiangce_urls.length / 3) * 3) {  //如果最后一行未全占满，需要更改部分样式才能平衡

        }
        if (item === 'addPic') {
            return <TouchableHighlight key={'ic-' + i} style={[styles.xiangce_image, {width: chicun, height: chicun}]}
                                       onPress={() => this.setState({addPicModalVisible: "1"})}>
                <Image source={require('shequnsiweiapp/src/img/camera.png')}/>
            </TouchableHighlight>
        } else {
            let imageStyle = [styles.xiangce_image]
            return (
                <ImageComponent key={'ic-' + i} source={item} width={chicun}
                                height={chicun} onPress={this.picView} styles={imageStyle}/>)
        }
    }

    genPhotoUI() {
        return (
            <View>
                <View style={[styles.tableRowTouch, {margin: 0, borderBottomWidth: 1}]}>
                    <Text style={styles.input_value_text}>相册</Text>
                </View>
                <View style={styles.xiangce_view}>
                    <GridView removeClippedSubviews={false} pageSize={100} initialListSize={5}
                              groupStyle={styles.xiangce_row} items={this.state.xiangce_urls} itemsPerRow={3}
                              renderItem={this.genPeopleInfoItemUI.bind(this)}/>
                </View>
                <ModalDropdown data={['拍照', '从手机相册选择']} clickEvent={this.addPic.bind(this)}
                               modalVisible={this.state.addPicModalVisible}/>
            </View>
        );
    }

    genSettingListOld() {
        return (
            <View>
                {this.genTableRowUI({
                    title: 'API-测试文档',
                    rightTitle: '查看',
                    onPress: this.onPressJumpToAPIList.bind(this),
                    showSplite: true,
                })}
                {this.genTableRowUI({title: '会员', rightTitle: '你还不是会员', rightButton: {title: '成为会员'}})}
                {this.genTableRowUI({title: '愿望币', rightTitle: '剩余:100', rightButton: {title: '去充值'}})}
                <View style={styles.rowBlank}/>
                {this.genTableRowUI({
                    title: '设置',
                    rightTitle: '',
                    jumpArrow: true,
                    onPress: this.setting.bind(this)
                })}
                {this.genPhotoUI()}
            </View>
        );
    }

    onPressJumpToSkillRenZheng = () => {
        // Util.showToast("跳转到 技能认证 界面")
        this.props.navigation.navigate('SkillRenZhengScene', {title: '技能认证'})
    }

    onPressJumpToOrderCenter = () => {
        // Util.showToast("跳转到 订单中心 界面")
        this.props.navigation.navigate('OrderCenterScene', {title: '订单中心'})
    }

    onPressJumpToOrderHistory = () => {
        // Util.showToast("跳转到 接单记录 界面")
        this.props.navigation.navigate('OrderHistoryScene', {title: '接单记录'})
    }

    render() {
        const settingList = [
            {
                icon: require('../../images/mine/mine_zizhi.png'),
                title: '认证技能资质',
                rightTitle: '2',
                onPress: this.onPressJumpToSkillRenZheng,
                jumpArrow: true,
                showSplite: true,
            },
            {
                icon: require('../../images/mine/mine_dingdan.png'),
                title: '订单中心',
                rightTitle: '3',
                onPress: this.onPressJumpToOrderCenter,
                jumpArrow: true,
                showSplite: true,
            },
            {
                icon: require('../../images/mine/mine_jiedanjilu.png'),
                title: '接单记录',
                rightTitle: '',
                onPress: this.onPressJumpToOrderHistory,
                jumpArrow: true,
                showSplite: true,
            },
            {
                icon: require('../../images/mine/mine_set.png'),
                title: '账号设置',
                rightTitle: '',
                jumpArrow: true,
                onPress: this.setting.bind(this),
                showSplite: true,
            },
        ];
        return (
            <View>
                {this.genHeaderUI()}
                <ScrollView style={styles.body}>
                    {settingList.map((item, index) => this.genTableRowUI(item, index))}
                </ScrollView>
            </View>
        )
    }

}


class VideoSpzt extends React.Component {
    render() {
        let spzt = this.props.spzt;
        if (spzt && spzt != '1') {
            let spztDesc;
            if (spzt === '0') {
                spztDesc = '视频认证审批中';
            } else if (spzt === '2') {
                spztDesc = '视频认证未通过';
            }
            return (
                <View style={[this.props.styles, {backgroundColor: '#393130'}]}>
                    <Text>{spztDesc}</Text>
                </View>
            );
        } else {
            return null;
        }
    }
}

const styles = StyleSheet.create({
    body: {
        backgroundColor: Color.VIEW_BG_COLOR,
        paddingTop: 8,
        height: '100%',
    },
    rowBlank: {
        height: 8,
    },
    tableRowItemPanel: {
        backgroundColor: 'white',
    },
    tableRowTouch: {
        flexDirection: "row",
        alignItems: "center",
        marginTop: 0,
        padding: 8,
        paddingLeft: 10,
        paddingRight: 10,
        minHeight: 48,
    },
    tableRowSplit: {
        height: Util.getRealPixel(1),
        backgroundColor: '#F1F1F1',
        marginLeft: 4,
    },
    arrowIcon: {
        marginLeft: 10,
        marginRight: 6,
    },
    tipBox: {
        backgroundColor: 'rgb(242, 168, 59)',
        alignItems: "center",
        marginLeft: 8,
        padding: 5,
    },
    input_label_view: {
        flex: 1, flexDirection: "row",
    },
    input_label_text: {
        alignSelf: "center",
    },
    input_value_view: {
        flex: 3,
        flexDirection: "row",
        alignItems: 'center',
        justifyContent: "flex-end",
        alignSelf: "center",
    },
    input_value_text: {
        color: Color.TEXT_HREF,
    },
    btn: {
        backgroundColor: Color.BTN_BGCOLOR,
        padding: 10,
        margin: 15,
        marginBottom: 0,
        borderRadius: 5,
    },
    btn_text: {
        alignSelf: 'center', fontSize: 15, color: Color.BTN_TEXT
    },
    xiangce_view: {
        marginTop: 0, backgroundColor: '#ffffff', flexDirection: "row",
    },
    xiangce_row: {
        flexDirection: "row",
        justifyContent: "space-between",//最后一行是flex-start
        marginLeft: 4,
        marginRight: 4,
        marginTop: 4,
        marginBottom: 0,
    },
    xiangce_image: {
        backgroundColor: Color.VIEW_BG_COLOR,
        flexDirection: "row",
        justifyContent: "center",
        alignItems: "center",
        marginRight: 2
    },
    headerPanel: {
        backgroundColor: '#7156E1'
    },
    headerPanelBg: {
        height: 100,
        backgroundColor: '#7156E1',
        width: '100%',
        flexDirection: 'row',
        justifyContent: "center",
        alignItems: "center",
    },
    headerBottomPanel: {
        backgroundColor: '#8A7BE9',
        height: 50,
        width: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerLeft: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerMid: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    headerRight: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    btnNext: {
        width: 20,
        height: 40,
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: 10,
        // borderWidth:1,
    },
    btnNextImage: {
        width: 7,
        height: 12,
    },
    btnNextImageSmall: {
        width: 7,
        height: 12,
    },
    accountTitle: {
        fontSize: 14,
        fontWeight: '600',
        color: 'white',
    },
    accountBottomTitle: {
        marginTop: 4,
        fontSize: 12,
        color: 'rgba(255,255,255,0.8)',
    },
    headerTopLeft: {
        width: 55,
        height: 55,
        borderRadius: 30,
        backgroundColor: Color.PRIMARY_COLOR,
        marginLeft: 10,
        marginRight: 5,
    },
    headerTopMid: {
        flex: 1,
    },
    headerNickName: {
        fontSize: 16,
        fontWeight: '600',
        color: 'white',
    },
    headerID: {
        marginTop: 10,
        fontSize: 12,
        color: 'rgba(255,255,255,0.8)',
    },
    tableRowIcon: {
        width: 17,
        height: 20,
        resizeMode: 'contain',
        marginRight: 15,
    },

});

module.exports = MineScene;

